import router, { resetRouter } from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Route } from "vue-router";
import i18n from "@/lang"; // Internationalization
import { AuthModule } from "./store/modules/auth";
import { SettingsModule } from "./store/modules/settings";
import { Message } from "element-ui";
import { AppModule } from "./store/modules/app";

NProgress.configure({ showSpinner: false });

const whiteList = ["/login/system_admin", "/login/tenant_admin", "/403", "/ram_forbidden","/faq", "/faq/content", "/faq/agreement", "/faq/policy", "/faq/protocol", "/notopened"];

const getPageTitle = (key: string | Function) => {
  if (typeof(key) === 'function') {
    key = key();
  }
  const hasKey = i18n.te(`route.${key}`);
  if (hasKey) {
    const pageName = i18n.t(`route.${key}`);
    
    return `${pageName} - 移动云云桌面管理平台`;
  }
  return '移动云云桌面管理平台';
};

router.beforeEach(async(to: Route, _: Route, next: any) => {
  // Start progress bar
  NProgress.start();
  // 判断是否为租户管理员

  console.log(AuthModule.is_cloud_manage_tenant_system, to.name, AuthModule.authrole)
  if (process.env.VUE_APP_AUTH_RULE === 'tenant_admin' && to.name !== 'SystemAdminLogin' && to.name != 'faq' && to.name != 'Policy' && to.name != 'Protocol' && to.name != 'Content' && to.name != 'Agreement' && to.name !== 'notopened' && to.name !== '403' && AuthModule.authrole == 'tenant_admin' && AuthModule.is_cloud_manage_tenant_system == false) {
    await AuthModule.getUserPermission();
  }
  if (AuthModule.is_cloud_manage_tenant_system == true) {
    // AuthModule.GetUserInfo();
    // AppModule.SetWorkOrderNumber();
    // if (new Date().getTime() - AuthModule.authGetTime.getTime() > SettingsModule.refreshTokenTime) {
    //   // AuthModule.Refresh();
    // }
    if (to.meta && to.meta.authrole && to.meta.authrole !== AuthModule.authrole) {
      Message.warning("你没有权限访问此页面");
      next(_);
    }
    next();
  } else {
     if (AuthModule.token) {
      AuthModule.GetUserInfo();
      AppModule.SetWorkOrderNumber();
      if (new Date().getTime() - AuthModule.authGetTime.getTime() > SettingsModule.refreshTokenTime) {
        AuthModule.Refresh();
      }
      if (to.meta && to.meta.authrole && to.meta.authrole !== AuthModule.authrole) {
        Message.warning("你没有权限访问此页面");
        next(_);
      }
      next();
    } else {
      if (whiteList.includes(to.path)) {
        next();
      } else {
        if (process.env.VUE_APP_AUTH_RULE === 'tenant_admin') {
          AuthModule.LogOut(false);
        } else if (process.env.VUE_APP_AUTH_RULE === 'system_admin') {
          AuthModule.LogOut(true);
        }
        // next({
        //   path: "/login/system_admin"
        // });
      }
    }
  }
});

router.afterEach((to: Route) => {
  // Finish progress bar
  NProgress.done();
  // set page title
  document.title = getPageTitle(to.meta ? to.meta.title : "");
});
